package com.taxshare.tools.util.sst;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.RawResponse;
import net.dongliu.requests.Requests;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class RequestKit {
    private RequestKit() {

    }

    static final String INPUT = "input";

    public static JSONObject request(String url, String publickey, String privatekey, String json)
            throws UnsupportedEncodingException {
        log.info("请求的私钥:" + privatekey);
        log.info("请求的文明:" + json);
        JSONObject requestjsonobj = JSON.parseObject(json);
        if (requestjsonobj.containsKey(INPUT)) {
            String inputstr = requestjsonobj.getJSONObject(INPUT).toJSONString();
            log.info(inputstr);
            String inputmi = AESUtil.encrypt(inputstr, privatekey);
            log.info("input内容加密:" + inputmi);
            requestjsonobj.put(INPUT, inputmi);
        }

        log.info(requestjsonobj.toJSONString());
        String requestjson = AESUtil.encrypt(requestjsonobj.toJSONString(), publickey);
        log.info("报文加密:" + requestjson);
        Map<String, String> reqbody = new HashMap<String, String>();
        reqbody.put("json", URLEncoder.encode(requestjson, "UTF-8"));
        RawResponse response = Requests.post(url).body(reqbody).verify(false).timeout(60000).send();
        String responsetext = response.readToText();
        log.info("接受返回报文：" + responsetext);
        JSONObject ret = JSON.parseObject(responsetext);
        String rawdata = ret.getString("data");
        if (rawdata != null && !rawdata.equals("")) {
            log.info(rawdata);
            String outdata = AESUtil.decrypt(rawdata, privatekey);
            log.info(outdata);
            Object jsonobj = JSON.parse(outdata);
            ret.put("data", jsonobj);
        }
        return ret;
    }

    public static void main(String[] args) {
        String inputstr = "{\"fplxdm\":\"026\"}";
        String privatekey = "e4163c65bdaa44f9";
        String inputmi = AESUtil.encrypt(inputstr, privatekey);
        System.out.println(inputmi);
    }
}
